package cn.swu.cs.lesson_13

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.android.material.appbar.MaterialToolbar
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.BufferedReader
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

/**
 * A simple [Fragment] subclass.
 * Use the [HomeFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class HomeFragment : Fragment() {

    lateinit var mAdapter :NewsListAdapter

    val NEW_URL = "https://api.apiopen.top/getWangYiNews"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mAdapter = NewsListAdapter()

        val drawer = view.findViewById<DrawerLayout>(R.id.drawer)

        view.findViewById<RecyclerView>(R.id.recycler).apply {
            this.layoutManager = LinearLayoutManager(view.context)
            this.adapter = mAdapter
        }
        view.findViewById<MaterialToolbar>(R.id.toolbar).setNavigationOnClickListener {
            if(!drawer.isDrawerOpen(GravityCompat.START)){
                drawer.openDrawer(GravityCompat.START)
            }
        }
        //loadByUrl()

    }



    private fun loadByUrl() {
        thread {
            val url = URL(NEW_URL)
            val connect = url.openConnection() as HttpURLConnection
            connect.requestMethod = "GET"
            val stream = connect.inputStream
            val allText = stream.bufferedReader().use(BufferedReader::readText)

            val data = parseJSONString(allText)
            Handler(Looper.getMainLooper()).post {
                mAdapter.resetData(data)
            }
        }
    }

    private fun parseJSONString(json: String): List<News> {
        val gson = Gson()
        val type = object : TypeToken<NewsResp>(){}.type
        val rs = gson.fromJson<NewsResp>(json,type)
        return rs.result
    }

    class NewsListAdapter : RecyclerView.Adapter<NewsListViewHolder>() {

        val data = arrayListOf<News>()

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsListViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_news,parent,false)

            return NewsListViewHolder(view).apply {
                this.img = view.findViewById(R.id.img)
                this.title = view.findViewById(R.id.title)
                this.time = view.findViewById(R.id.time)
            }
        }

        override fun onBindViewHolder(holder: NewsListViewHolder, position: Int) {
            holder.render(data[position])
        }

        override fun getItemCount(): Int {
            return data.size
        }

        fun resetData(arr: List<News>) {
            data.clear()
            data.addAll(arr)
            notifyDataSetChanged()
        }

    }

    class NewsListViewHolder(val view: View): RecyclerView.ViewHolder(view){


        var img: ImageView? = null
        var title: TextView? = null
        var time: TextView? = null

        fun render(news: News) {
            title?.text = news.title
            time?.text = news.passtime
            //
            // img.setImageURI()
            Glide.with(view).load(news.image).into(img!!)
        }
    }

}